<template>
  <div class="area-container">
    <el-card>
      <!-- 显示排列表 -->
      <el-row :gutter="20" class="centered-row">
        <el-col v-for="row in rowsInArea" :key="row" :span="8" class="mb-20">
          <el-card shadow="hover" class="row-card">
            <div slot="header" class="clearfix">
              <span>{{ row }}排</span>
              <el-button
                style="float: right; padding: 3px 0"
                type="text"
                @click.stop="handleViewRow(row)"
              >
                查看详情
              </el-button>
            </div>
            <!-- 显示可用柜子数量 -->
            <div class="row-info">
              可用：{{ availableCabinetsInRow(row) }} / 总数：{{ totalCabinetsInRow(row) }}
            </div>
            <!-- 快速使用按钮 -->
            <div class="row-actions">
               <el-button
                 v-if="availableCabinetsInRow(row) > 0"
                 type="success"
                 size="mini"
                 @click.stop="handleQuickUseCabinet(row)"
               >
                 快速使用可用柜子
               </el-button>
            </div>
            <!-- 这里不显示具体的柜子，只显示排号和查看详情按钮 -->
          </el-card>
        </el-col>
      </el-row>

      <!-- 渲染子路由组件 (Row.vue) -->
      <router-view />

    </el-card>

    <!-- 柜子操作对话框 (保留对话框，虽然可能主要在 Row 或 Detail 使用) -->
    <!-- 暂时保留，后续看是否需要移动 -->
     <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="30%">
      <div v-if="selectedCabinet">
        <p>柜子编号：{{ selectedCabinet.id }}</p>
        <p>状态：{{ getStatusText(selectedCabinet.status) }}</p>
        <template v-if="selectedCabinet.status === 'available'">
          <el-button type="primary" @click="handleUseCabinet">使用柜子</el-button>
        </template>
        <template v-else-if="selectedCabinet.status === 'in_use'">
          <p>开始时间：{{ formatDate(selectedCabinet.startTime) }}</p>
          <p>使用密码：{{ selectedCabinet.password }}</p>
          <el-button 
            type="danger" 
            @click="handleReleaseCabinet"
            v-if="selectedCabinet.userId === user.id"
          >释放柜子</el-button>
          <p v-else class="text-warning">只有使用者才能释放柜子</p>
        </template>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { mapState } from "vuex";

export default {
  name: "AreaCabinets",
  data() {
    return {
      dialogVisible: false,
      selectedCabinet: null
    };
  },
  computed: {
    ...mapState({
      user: (state) => state.user,
      allRows: (state) => state.cabinets.rows, // 获取所有行的信息
      allCabinets: (state) => state.cabinets.cabinets // 获取所有柜子
    }),
    area() {
      return this.$route.params.area;
    },
    rowsInArea() {
        return this.allRows[this.area] || [];
    },
    isAdmin() {
      return this.user && this.user.role === "admin";
    },
    dialogTitle() {
      return this.selectedCabinet ? `柜子 ${this.selectedCabinet.id} 详情` : "柜子详情";
    }
  },
   watch: {
    // 监听路由变化，确保 area 参数有效
    '$route.params.area': {
      immediate: true,
      handler(newArea) {
        if (!newArea || !this.allRows[newArea]) {
           // 如果 area 参数无效，导航回 /cabinets
           this.$router.replace('/cabinets').catch(()=>{});
        }
      }
    }
  },
  methods: {
    // 根据区域和排过滤柜子
    getCabinetsByAreaAndRow(area, row) {
      if (!this.allCabinets) return [];
      return Object.values(this.allCabinets).filter(
        cabinet => cabinet.area === area && cabinet.row === row
      );
    },
    // 计算某个排的总柜子数
    totalCabinetsInRow(row) {
      return this.getCabinetsByAreaAndRow(this.area, row).length;
    },
    // 计算某个排的可用柜子数
    availableCabinetsInRow(row) {
      return this.getCabinetsByAreaAndRow(this.area, row).filter(
        cabinet => cabinet.status === 'available'
      ).length;
    },
    getStatusText(status) {
      const statusMap = {
        available: "空闲",
        in_use: "使用中"
      };
      return statusMap[status] || status;
    },
    formatDate(date) {
      if (!date) return "-";
      return new Date(date).toLocaleString();
    },
    handleViewRow(row) {
      // 导航到 Row 级别的路由
      this.$router.push(`/cabinets/${this.area}/${row}`).catch(() => {}); // 导航并捕获错误
    },
    // 处理快速使用柜子
    async handleQuickUseCabinet(row) {
      const available = this.getCabinetsByAreaAndRow(this.area, row).find(
        cabinet => cabinet.status === 'available'
      );
      if (available) {
        try {
          // 调用 Vuex action 来使用柜子
          // 假设 useCabinet action 返回使用后的柜子信息，包含密码
          const usedCabinet = await this.$store.dispatch('useCabinet', { cabinetId: available.id, userId: this.user.id });
          this.$message.success(`成功使用柜子 ${available.id}，取件密码：${usedCabinet.password}`);
           // 刷新当前区域的数据或者直接更新 affected cabinet state
           // 对于 Area.vue，由于 watch 监听 cabinets 变化，state 更新会自动反映
        } catch (error) {
          this.$message.error(error.message || '快速使用失败');
        }
      } else {
        this.$message.warning('该排暂无可用柜子');
      }
    },
    async handleUseCabinet() { /* ... */ },
    async handleReleaseCabinet() { /* ... */ }
  }
};
</script>

<style scoped>
.area-container {
  padding: 20px;
}

.mb-20 {
  margin-bottom: 20px;
}

.row-card {
  margin-bottom: 20px;
}

.row-info {
    padding: 10px;
    text-align: center;
    color: #909399;
}

.row-actions {
  text-align: center;
  padding-bottom: 10px;
}

/* 以下样式可能主要在 Row 和 Detail 组件中使用，Area 中不再需要 */
/*
.cabinet-grid { ... }
.cabinet-item { ... }
.cabinet-item.available { ... }
.cabinet-item.in_use { ... }
.cabinet-item.maintenance { ... }
.cabinet-number { ... }
.cabinet-status { ... }
*/

.centered-row {
  display: flex; /* el-row is already flex by default */
  justify-content: center; /* Center the flex items (el-col) */
}

</style>
